﻿using DAL;
using BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
public partial class admincp_Products : System.Web.UI.Page
{
    DigitalWorldDataContext db = new DigitalWorldDataContext();
    ProductsBLL pro = new ProductsBLL();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string vt = Page.RouteData.Values["ViTri"].ToString();

            hlBasicProduct.NavigateUrl = "~/Quan-Ly-San-Pham/" + vt + "/" + 0;
            hlInfoLaptop.NavigateUrl = "~/Quan-Ly-San-Pham/" + vt + "/" + 1;
            hlInfoPhone.NavigateUrl = "~/Quan-Ly-San-Pham/" + vt + "/" + 2;
            string id = Page.RouteData.Values["id"].ToString();
            if (id == "1")
            {
                MutiView1.ActiveViewIndex = 1;
                LoadData_Products_by_LapTop_Tablet();
                btnUpdateLapTop.Enabled = false;
            }
            else if (id == "2")
            {
                MutiView1.ActiveViewIndex = 2;
                LoadData_Phone();
                btnUpdate_Phone.Enabled = false;
            }
            else
            {
                MutiView1.ActiveViewIndex = 0;
                LoadDDL_Products();
                LoadData_Products();
                btnUpdate.Enabled = false;
                rbtnDiscountinued.Enabled = false;
            }
        }
    }

    #region Basic Information
    #region Load Supplier By CategoryID
    /// <summary>
    /// Hàm lấy dữ liệu supplier theo catid của categories
    /// </summary>
    /// <param name="CateID"></param>
    void LoadSupplierByCategory(string CateID)
    {
        var danhsach = from sc in db.Sup_Categories
                       join s in db.suppliers
                       on sc.SupID equals s.supplierid
                       where sc.CateID == CateID
                       select new
                       {
                           SupID = sc.SupID,
                           companyname = s.companyname
                       };
        ddlSupplier.DataSource = danhsach;
        ddlSupplier.DataTextField = "companyname";
        ddlSupplier.DataValueField = "SupID";
        ddlSupplier.DataBind();
    }
    #endregion
    

    #region Load Categories - Suppliers - Origins
    /// <summary>
    /// Hàm lấy dữ liệu các bảng category,supplier theo catid, origins lên dropdownlist
    /// </summary>
    void LoadDDL_Products()
    {
        ddlCategory.DataSource = db.categories;
        ddlCategory.DataTextField = "categoryname";
        ddlCategory.DataValueField = "categoryid";
        ddlCategory.DataBind();
        ddlCategory.SelectedIndex = 0;

        LoadSupplierByCategory(ddlCategory.SelectedValue);

        ddlOrigin.DataSource = db.origins;
        ddlOrigin.DataTextField = "countryname";
        ddlOrigin.DataValueField = "originid";
        ddlOrigin.DataBind();
    }
    #endregion
    

    #region Load Basic Product to GridView
    /// <summary>
    /// Hàm lấy dữ liệu từ bảng product lên gridview
    /// </summary>
    void LoadData_Products()
    {
        gvProduct.DataSource = db.products.OrderByDescending(p=>p.productid);
        gvProduct.DataBind();
    }

    protected void ddlCategory_SelectedIndexChanged1(object sender, EventArgs e)
    {
        LoadSupplierByCategory(ddlCategory.SelectedValue);
    }
    #endregion
    
    #region Hàm nhận giá trị cơ bản
    /// <summary>
    /// Hàm nhận giá trị vào lớp product từ các textbox ở trang thông tin cơ bản
    /// </summary>
    /// <param name="ProID"></param>
    //void Products_BasicInfor(int ProID)
    //{
        //p.productid = ProID;
        //p.categoryid = ddlCategory.SelectedItem.Value;
        //p.originid = ddlOrigin.SelectedItem.Value;
        //p.supplierid = int.Parse(ddlSupplier.SelectedItem.Value);
        //p.productname = txtProductName.Text;
        //p.description = txtDescription.Text;
        //p.photopath = SaveImage();
        //p.dateupdated = DateTime.Now.Date;
        //p.unitprice = Decimal.Parse(txtUnitPrice.Text);
        //p.unitprice_sell = decimal.Parse(txtUnitPrice_Sell.Text);
        //p.unitsinstock = int.Parse(txtUnitsInStock.Text);
        //p.unitsonorder = int.Parse(txtUnitsOnOrder.Text);
        //p.discount = double.Parse(txtDiscount.Text);
        //if (rbtnDiscountinued.SelectedItem.Value == "1")
        //{
        //    p.discontinued = true;
        //}
        //else
        //{
        //    p.discontinued = false;
        //}
    //}
    #endregion
    
    #region Reset TextBox View Basic Product
    /// <summary>
    /// Hàm xoá trắng các textbox trên trang thông tin cơ bản
    /// </summary>
    void ResetTextBox()
    {
        txtProductName.Text = string.Empty;
        ddlCategory.SelectedIndex = 0;
        LoadSupplierByCategory(ddlCategory.SelectedValue);
        ddlOrigin.SelectedIndex = 0;
        txtUnitsInStock.Text = string.Empty;
        txtUnitsOnOrder.Text = string.Empty;
        txtUnitPrice.Text = string.Empty;
        txtUnitPrice_Sell.Text = string.Empty;
        txtDiscount.Text = string.Empty;
        txtDescription.Text = string.Empty;
        imgPhotoPath.ImageUrl = null;
        txtProductName.Focus();
    }
    #endregion
    
    #region Lưu hình sản phẩm
    /// <summary>
    /// Hàm lưu hình sản phẩm từ FileUpLoad
    /// </summary>
    /// <returns></returns>
    private string SaveImage()
    {
        string savename = string.Empty;
        if (!string.IsNullOrEmpty(ful_upload.FileName.ToString()))
        {
            int count = db.products.Count();
            string tenhinh = "Digital_World_" + ddlCategory.SelectedItem.Text + "_" +
                ddlSupplier.SelectedItem.Text + "_" + count + "_" + txtProductName.Text;
            int vitri = ful_upload.FileName.LastIndexOf('.');
            string tail = ful_upload.FileName.Substring(vitri);
            if (tail.ToLower() == ".jpg" || tail.ToLower() == ".png" || tail.ToLower() == ".gif")
            {
                savename = tenhinh + tail;
                string savePath = Server.MapPath("../../Image/Products/");
                ful_upload.SaveAs(savePath + savename);
            }
        }
        return savename;
    }
    #endregion

    #region Methods Button Insert - Update - Grid View Event SelectIndexChanging
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        try
        {
            product p = new product
            {
                productname = txtProductName.Text,
                categoryid = ddlCategory.SelectedItem.Value,
                supplierid = int.Parse(ddlSupplier.SelectedItem.Value),
                originid = ddlOrigin.SelectedItem.Value,
                description = txtDescription.Text,
                photopath = SaveImage(),
                dateupdated = DateTime.Now.Date,
                unitprice = Decimal.Parse(txtUnitPrice.Text),
                unitprice_sell = Decimal.Parse(txtUnitPrice_Sell.Text),
                unitsinstock = int.Parse(txtUnitsInStock.Text),
                unitsonorder = int.Parse(txtUnitsOnOrder.Text),
                discount = Double.Parse(txtDiscount.Text)
            };
            pro.InsertBasicProduct(p);
            this.LoadData_Products();
            ResetTextBox();
            lblThongBao.Text = "Thành công";
        }
        catch
        {
            lblThongBao.Text = "Thất bại";
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            int ProductID = int.Parse(gvProduct.SelectedRow.Cells[0].Text);
            bool discontinued;
            if (rbtnDiscountinued.SelectedItem.Value == "1")
            {
                discontinued = true;
            }
            else
            {
                discontinued = false;
            }
            product p = new product
            {
                productid = ProductID,
                categoryid = ddlCategory.SelectedItem.Value,
                originid = ddlOrigin.SelectedItem.Value,
                supplierid = int.Parse(ddlSupplier.SelectedItem.Value),
                productname = txtProductName.Text,
                description = txtDescription.Text,
                photopath = SaveImage(),
                dateupdated = DateTime.Now.Date,
                unitprice = Decimal.Parse(txtUnitPrice.Text),
                unitprice_sell = Decimal.Parse(txtUnitPrice_Sell.Text),
                unitsinstock = int.Parse(txtUnitsInStock.Text),
                unitsonorder = int.Parse(txtUnitsOnOrder.Text),
                discount = double.Parse(txtDiscount.Text),
                discontinued = discontinued
            };
            pro.UpdateBasicProduct(p);
            ResetTextBox();
            btnUpdate.Enabled = false;
            this.LoadData_Products();
            lblThongBao.Text = "Thành công";
        }
        catch
        {
            lblThongBao.Text = "Thất bại";
        }
    }
    protected void gvProduct_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        int ProductID = int.Parse(gvProduct.Rows[e.NewSelectedIndex].Cells[0].Text);
        var danhsach = db.products.SingleOrDefault(pr => pr.productid.Equals(ProductID));
        txtProductName.Text = danhsach.productname;
        ddlSupplier.SelectedValue = danhsach.supplierid.ToString(); ;
        ddlCategory.SelectedValue = danhsach.categoryid;
        ddlOrigin.SelectedValue = danhsach.originid;
        txtUnitsInStock.Text = danhsach.unitsinstock.ToString();
        txtUnitsOnOrder.Text = danhsach.unitsonorder.ToString();
        txtUnitPrice.Text = danhsach.unitprice.ToString();
        txtUnitPrice_Sell.Text = danhsach.unitprice_sell.ToString();
        txtDiscount.Text = danhsach.discount.ToString();
        txtDescription.Text = danhsach.description;
        imgPhotoPath.ImageUrl = "~/Image/Products/" + danhsach.photopath.ToString();
        if (danhsach.discontinued == true)
            rbtnDiscountinued.SelectedIndex = 0;
        else
            rbtnDiscountinued.SelectedIndex = 1;
        btnUpdate.Enabled = true;
        rbtnDiscountinued.Enabled = true;
    }
    #endregion

    #endregion

    #region Details Information about LapTops_Tablets
    void LoadData_Products_by_LapTop_Tablet()
    {
        gvInfoProducts_Laptop_Tablet.DataSource = db.products.Where
            (pr => pr.categoryid == "TKW" || pr.categoryid == "TL").OrderByDescending(p => p.productid);
        gvInfoProducts_Laptop_Tablet.DataBind();
    }
    void ResetTextBox_Products_by_LapTop_Tablet()
    {
        txtManufacturerName.Text = string.Empty;
        txtTechnologyCPU.Text = string.Empty;
        txtTypeCPU.Text = string.Empty;
        txtSpeedCPU.Text = string.Empty;
        txtOtherInfoCPU.Text = string.Empty;
        txtStorageRAM.Text = string.Empty;
        txtBusSpeed.Text = string.Empty;
        txtDiskSpace.Text = string.Empty;
        txtRotationalSpeed.Text = string.Empty;
        txtTouchScreen.Text = string.Empty;
        txtSizeMH.Text = string.Empty;
        txtGraphicsChipset.Text = string.Empty;
        txtGraphicsSpace.Text = string.Empty;
        txtOtherInfoGraphics.Text = string.Empty;
        txtOpticalDiscs.Text = string.Empty;
        txtInterface.Text = string.Empty;
        txtExtendedFeatures.Text = string.Empty;
        txtWiFiStandard.Text = string.Empty;
        txtWirelessConnection.Text = string.Empty;
        txtWebCam.Text = string.Empty;
        txtBatteryInfomation.Text = string.Empty;
        txtUseTime.Text = string.Empty;
        txtOS.Text = string.Empty;
        txtOtherInfoOS.Text = string.Empty;
        txtManufacturerName.Focus();
    }
    void LoadTextBox_Products_by_LapTop_Tablet(int ProductID)
    {
        //int ProductID = int.Parse(gvInfoProducts_Laptop_Tablet.SelectedRow.Cells[0].Text);
        var danhsach = db.products.SingleOrDefault
            (pr => pr.productid.Equals(ProductID));
        imgPhotoPath_Laptop.ImageUrl = "~/Image/Products/" + danhsach.photopath;
        txtManufacturerName.Text = danhsach.manufacturername;
        txtTechnologyCPU.Text = danhsach.technologycpu;
        txtTypeCPU.Text = danhsach.typecpu;
        txtSpeedCPU.Text = danhsach.speedcpu;
        txtOtherInfoCPU.Text = danhsach.otherinfocpu;
        txtStorageRAM.Text = danhsach.storageram;
        txtBusSpeed.Text = danhsach.busspeed;
        txtDiskSpace.Text = danhsach.diskspace;
        txtRotationalSpeed.Text = danhsach.rotationalspeed;
        txtTouchScreen.Text = danhsach.touchscreen;
        txtSizeMH.Text = danhsach.sizemh.ToString();
        txtGraphicsChipset.Text = danhsach.graphicschipset;
        txtGraphicsSpace.Text = danhsach.graphicsspace;
        txtOtherInfoGraphics.Text = danhsach.otherinfographics;
        txtOpticalDiscs.Text = danhsach.opticaldiscs;
        txtInterface.Text = danhsach.@interface;
        txtExtendedFeatures.Text =danhsach.extendedfeatures;
        txtWiFiStandard.Text = danhsach.wifistandard;
        txtWirelessConnection.Text = danhsach.wirelessconnection;
        txtWebCam.Text = danhsach.webcam;
        txtBatteryInfomation.Text = danhsach.batteryinformation;
        txtUseTime.Text = danhsach.usetime;
        txtOS.Text = danhsach.os;
        txtOtherInfoOS.Text = danhsach.otherinfoos;
    }
    protected void btnUpdateLapTop_Click(object sender, EventArgs e)
    {
        try
        {
            product p = new product { 
            productid = int.Parse(gvInfoProducts_Laptop_Tablet.SelectedRow.Cells[0].Text),
            manufacturername = txtManufacturerName.Text,
            technologycpu = txtTechnologyCPU.Text,
            typecpu = txtTypeCPU.Text,
            speedcpu = txtSpeedCPU.Text,
            otherinfocpu = txtOtherInfoCPU.Text,
            storageram = txtStorageRAM.Text,
            busspeed = txtBusSpeed.Text,
            diskspace = txtDiskSpace.Text,
            rotationalspeed = txtRotationalSpeed.Text,
            touchscreen = txtTouchScreen.Text,
            sizemh = int.Parse(txtSizeMH.Text),
            graphicschipset = txtGraphicsChipset.Text,
            graphicsspace = txtGraphicsSpace.Text,
            otherinfographics = txtOtherInfoGraphics.Text,
            opticaldiscs = txtOpticalDiscs.Text,
            @interface = txtInterface.Text,
            extendedfeatures = txtExtendedFeatures.Text,
            wifistandard = txtWiFiStandard.Text,
            wirelessconnection = txtWirelessConnection.Text,
            webcam = txtWebCam.Text,
            batteryinformation = txtBatteryInfomation.Text,
            usetime = txtUseTime.Text,
            os = txtOS.Text,
            otherinfoos = txtOtherInfoOS.Text,
            };
            pro.UpdateLaptopTablet(p);
            ResetTextBox_Products_by_LapTop_Tablet();
            btnUpdateLapTop.Enabled = false;
            LoadData_Products_by_LapTop_Tablet();
            lblThongBao.Text = "Thành công";
        }
        catch
        {
            lblThongBao.Text = "Thất bại";
        }
    }
    protected void gvInfoProducts_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        int ProductID = int.Parse(gvInfoProducts_Laptop_Tablet.Rows[e.NewSelectedIndex].Cells[0].Text);
        LoadTextBox_Products_by_LapTop_Tablet(ProductID);
        btnUpdateLapTop.Enabled = true;
    }
    protected void gvInfoProducts_Laptop_Tablet_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvInfoProducts_Laptop_Tablet.PageIndex = e.NewPageIndex;
        this.LoadData_Products_by_LapTop_Tablet();
    }
    #endregion

    #region Details Information about Mobile Phone

    void LoadData_Phone()
    {
        gvInfoProduct_Phone.DataSource = db.products.Where
            (pr => pr.categoryid == "PM").OrderByDescending(p => p.productid);
        gvInfoProduct_Phone.DataBind();
    }
    void ResetTextBox_Phone()
    {
        txtCamera.Text=string.Empty;
        txtMovie.Text=string.Empty;
        txtMusic.Text=string.Empty;
        txtFMRadio.Text=string.Empty;
        txtOtherApplication.Text=string.Empty;
        txtRecord.Text=string.Empty;
        txtRingtones.Text=string.Empty;
        txtHeadPhone.Text=string.Empty;
        txtMemory.Text=string.Empty;
        txtSDCardSupport.Text=string.Empty;
        txtContacts.Text=string.Empty;
        txtMobileNetwork.Text=string.Empty;
        txtGPRS.Text=string.Empty;
        txtNetwork3G.Text=string.Empty;
        txtGPS.Text=string.Empty;
        txtBluetooth.Text=string.Empty;
        txtUSB.Text=string.Empty;
        txtTypeScreen.Text=string.Empty;
        txtResolution.Text=string.Empty;
        txtSizePhone.Text=string.Empty;
        txtOS_Phone.Text=string.Empty;
        txtKeyboardQwerty.Text=string.Empty;
        txtWeight.Text=string.Empty;
        txtLanguage.Text=string.Empty;
        txtBatteryInfomation_Phone.Text=string.Empty;
        txtUseTime_Phone.Text=string.Empty;
        txtTalkTime.Text=string.Empty;
        txtWaitTime.Text=string.Empty;
        txtOtherInfoPhone.Text = string.Empty;
        txtCamera.Focus();
    }
    void LoadTextBox_Phone(int ProductID)
    {
        var danhsach=db.products.SingleOrDefault
            (pr=>pr.productid==ProductID);
        imgPhotoPath_Phone.ImageUrl = "~/Image/Products/" + danhsach.photopath;
        txtCamera.Text=danhsach.camera;
        txtMovie.Text=danhsach.movie;
        txtMusic.Text=danhsach.music;
        txtFMRadio.Text=danhsach.fmradio;
        txtOtherApplication.Text=danhsach.otherapplication;
        txtRecord.Text=danhsach.record;
        txtRingtones.Text=danhsach.ringtones;
        txtHeadPhone.Text=danhsach.headphone;
        txtMemory.Text=danhsach.memory;
        txtSDCardSupport.Text=danhsach.sdcardsupport;
        txtContacts.Text=danhsach.contacts;
        txtMobileNetwork.Text=danhsach.mobilenetwork;
        txtGPRS.Text=danhsach.gprs;
        txtNetwork3G.Text=danhsach.network3g;
        txtGPS.Text=danhsach.gps;
        txtBluetooth.Text=danhsach.bluetooth;
        txtUSB.Text=danhsach.usb;
        txtTypeScreen.Text=danhsach.typescreen;
        txtResolution.Text=danhsach.resolution;
        txtSizePhone.Text=danhsach.sizephone;
        txtOS_Phone.Text=danhsach.os;
        txtKeyboardQwerty.Text=danhsach.keyboardqwerty;
        txtWeight.Text=danhsach.weight;
        txtLanguage.Text=danhsach.language;
        txtBatteryInfomation_Phone.Text=danhsach.batteryinformation;
        txtUseTime_Phone.Text=danhsach.usetime;
        txtTalkTime.Text=danhsach.talktime;
        txtWaitTime.Text=danhsach.waittime;
        txtOtherInfoPhone.Text = danhsach.otherinfophone;
    }
    protected void gvInfoProduct_Phone_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvInfoProduct_Phone.PageIndex = e.NewPageIndex;
        LoadData_Phone();
    }
    protected void gvInfoProduct_Phone_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        int ProductID = int.Parse(gvInfoProduct_Phone.Rows[e.NewSelectedIndex].Cells[0].Text);
        LoadTextBox_Phone(ProductID);
        btnUpdate_Phone.Enabled = true;
    }
    protected void btnUpdate_Phone_Click(object sender, EventArgs e)
    {
        try{
            product p = new product { 
            productid = int.Parse(gvInfoProduct_Phone.SelectedRow.Cells[0].Text),
            camera = txtCamera.Text,
            movie = txtMovie.Text,
            music = txtMusic.Text,
            fmradio = txtFMRadio.Text,
            otherapplication = txtOtherApplication.Text,
            record = txtRecord.Text,
            ringtones = txtRingtones.Text,
            headphone = txtHeadPhone.Text,
            memory = txtMemory.Text,
            sdcardsupport = txtSDCardSupport.Text,
            contacts = txtContacts.Text,
            mobilenetwork = txtMobileNetwork.Text,
            gprs = txtGPRS.Text,
            network3g = txtNetwork3G.Text,
            gps= txtGPS.Text,
            bluetooth = txtBluetooth.Text,
            usb = txtUSB.Text,
            typescreen = txtTypeScreen.Text,
            resolution = txtResolution.Text,
            sizephone = txtSizePhone.Text,
            os = txtOS_Phone.Text,
            keyboardqwerty = txtKeyboardQwerty.Text,
            weight = txtWeight.Text,
            language = txtLanguage.Text,
            batteryinformation = txtBatteryInfomation_Phone.Text,
            usetime = txtUseTime_Phone.Text,
            talktime = txtTalkTime.Text,
            waittime = txtWaitTime.Text,
            otherinfophone = txtOtherInfoPhone.Text,
            };
            pro.UpdatePhone(p);
            ResetTextBox_Phone();
            btnUpdate_Phone.Enabled = false;
            LoadData_Phone();
            lblThongBao.Text = "Thành công";
        }
        catch
        {
            lblThongBao.Text = "Thất bại";
        }
    }
    #endregion


    protected void gvProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvProduct.PageIndex = e.NewPageIndex;
        this.LoadData_Products();
    }
}